import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/layout' },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    {
      path: '/layout',
      component: () => import('@/views/layout/index.vue'),
      children: [
        { path: '', redirect: '/home' },
        { path: '/home', component: () => import('@/views/layout/home.vue') },
        { path: '/user', component: () => import('@/views/layout/user.vue') },
        { path: '/category', component: () => import('@/views/layout/category.vue') },
        { path: '/cart', component: () => import('@/views/layout/cart.vue') }
      ]
    },
    { path: '/search', component: () => import('@/views/search/index.vue') },
    { path: '/myorder', component: () => import('@/views/myorder/index.vue') },
    { path: '/searchlist', component: () => import('@/views/search/searchlist.vue') },
    { path: '/prodetail/:id', component: () => import('@/views/prodetail/index.vue') },
    { path: '/pay', component: () => import('@/views/pay/index.vue') }
  ]
})
const authUrl = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  if (!authUrl.includes(to.path)) return next()
  const token = store.state.user.userInfo.token
  console.log(token)
  if (!token) {
    next('/login')
  } else {
    next()
  }
  // 已经登录，放行
})
export default router
